package com.qian.ddj.web.controller;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.qian.api.ddj.model.AliCode;
import com.qian.api.ddj.model.Business;
import com.qian.api.ddj.service.IAliCodeService;
import com.qian.api.ddj.service.IBusinessService;
import com.yaowk.api.common.BaseException;
import com.yaowk.api.common.PageReq;
import com.yaowk.api.common.PageResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/ddj/aliCode")
public class AliCodeController {

    @Autowired
    private IAliCodeService aliCodeService;
    @Autowired
    private IBusinessService businessService;

    @PostMapping("/upload")
    public void upload(MultipartFile file) throws IOException, NotFoundException {
        String fileName = file.getOriginalFilename();
        fileName = fileName.replaceFirst(".png|.jpg", "");
        BufferedImage image = ImageIO.read(file.getInputStream());
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        MultiFormatReader formatReader = new MultiFormatReader();
        Result result = formatReader.decode(binaryBitmap, hints);
        String qrCode = result.getText();

        String[] ss = fileName.split("-");
        AliCode aliCode = new AliCode();
        aliCode.setBusinessId(Integer.valueOf(ss[0]));
        aliCode.setRemark(fileName);
        aliCode.setAmount(new BigDecimal(ss[1]));
        aliCode.setQrCode(qrCode);
        Business business = businessService.findById(aliCode.getBusinessId());
        if (ObjectUtils.isEmpty(business)) {
            throw new BaseException("商户不存在");
        }
        aliCodeService.save(aliCode);
    }

    @GetMapping("/list/{businessId}")
    public PageResp<AliCode> list(@PathVariable Integer businessId, PageReq pageReq) {
        AliCode aliCode = new AliCode();
        aliCode.setBusinessId(businessId);
        PageResp<AliCode> all = aliCodeService.findAll(aliCode, pageReq);
        return all;
    }

    @PostMapping
    public void save(AliCode aliCode) {
        aliCodeService.save(aliCode);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        aliCodeService.deleteById(id);
    }

    @GetMapping("verifyCode/{id}")
    public List<String> verifyCode(@PathVariable Integer id, Integer beginMoney, Integer endMoney, Integer interval, Integer number, Integer offSet) {
        if (beginMoney == null || endMoney == null || number == null || interval == null || offSet == null) {
            throw new BaseException("参数不允许空");
        }

        AliCode aliCode = new AliCode();
        aliCode.setBusinessId(id);
        List<AliCode> aliCodes = aliCodeService.findAll(aliCode);
        Set<String> remarks = new TreeSet<>();
        for (AliCode aliCode1 : aliCodes) {
            remarks.add(aliCode1.getRemark());
        }

        String template = "%s-%s-%s";

        List<String> result = new ArrayList<>();
        for (int i = beginMoney; i <= endMoney; i += interval) {
            for (int j = 1; j <= number; j++) {
                String num = String.valueOf(j);
                String money = String.valueOf(i + offSet);
                if (j < 10) {
                    num = "0" + j;
                }
                String remark = String.format(template, id, money, num);
                if (!remarks.contains(remark)) {
                    result.add(remark);
                }
            }
        }

        return result;

    }

//根据金额查询
    @GetMapping("/findCode/{id}")
    public List<String> findCode(@PathVariable Integer id, Integer beginMoney, Integer endMoney, Integer interval, Integer number, Integer offSet) {//interval间隔 offSet偏移
        if (beginMoney == null || endMoney == null || number == null || interval == null || offSet == null) {
            throw new BaseException("参数不允许空");
        }
        AliCode aliCode = new AliCode();
        aliCode.setBusinessId(id);
        List<AliCode> aliCodes = aliCodeService.findAll(aliCode);
        Set<String> remarks = new TreeSet<>();
        for (AliCode aliCode1 : aliCodes) {
            remarks.add(aliCode1.getRemark());
        }
        String template = "%s-%s-%s";

        List<String> result = new ArrayList<>();
        for (int i = beginMoney; i <= endMoney; i += interval) {
            for (int j = 1; j <= number; j++) {
                String num = String.valueOf(j);
                String money = String.valueOf(i + offSet);
                if (j < 10) {
                    num = "0" + j;
                }
                String remark = String.format(template, id, money, num);
                if (remarks.contains(remark)) {
                    result.add(remark);
                }
            }
        }
        return result;
    }

    @DeleteMapping("/deleteCode/{id}")
    public void deleteCode(@PathVariable Integer id, Integer beginMoney, Integer endMoney, Integer interval, Integer number, Integer offSet) {//interval间隔 offSet偏移
        if (beginMoney == null || endMoney == null || number == null || interval == null || offSet == null) {
            throw new BaseException("参数不允许空");
        }
        AliCode aliCode = new AliCode();
        aliCode.setBusinessId(id);
        List<AliCode> aliCodes = aliCodeService.findAll(aliCode);
        Set<String> remarks = new TreeSet<>();
        for (AliCode aliCode1 : aliCodes) {
            remarks.add(aliCode1.getRemark());
        }
        String template = "%s-%s-%s";

        List<AliCode> result = new ArrayList<>();
        for (int i = beginMoney; i <= endMoney; i += interval) {
            for (int j = 1; j <= number; j++) {
                String num = String.valueOf(j);
                String money = String.valueOf(i + offSet);
                if (j < 10) {
                    num = "0" + j;
                }
                String remark = String.format(template, id, money, num);
                if (remarks.contains(remark)) {
                    AliCode aliCode2 = new AliCode();
                    aliCode2.setRemark(remark);
                    result.add(aliCodeService.findOne(aliCode2));
                }
            }
        }
        Iterator<AliCode> iter = result.iterator();
        while(iter.hasNext()){
            AliCode b = iter.next();
            aliCodeService.deleteById(b.getId());
        }
    }
}
